package com.dianshang.controller.file;

import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    // @Autowired
    // private HttpServletRequest request;

    /**
     * SpringMVC接收图片上传
     */
    @RequestMapping("/zhaoyu1")
    public String zhaoyu1(@RequestParam("file") MultipartFile picFile,HttpServletRequest request){

        String image = "";

        if (picFile.getSize()>0){

            String realPath = request.getSession().getServletContext().getRealPath("/");
            File file = new File(realPath, "/img/");
            if (!file.exists())file.mkdirs();
            String originalFilename = picFile.getOriginalFilename();

            try {
                picFile.transferTo(new File(file,originalFilename));
                image = "../img/"+originalFilename;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return "http://localhost:9101/img/"+image;

    }

    @Autowired
    private OSSClient ossClient;

    /**
     * OSS图片上传
     */
    @PostMapping("/zhaoyu2")
    public String zhaoyu2(@RequestParam("file") MultipartFile picFile,String yuchen){

        String bucketName = "zhaoyu-dianshang";
        String fileName= yuchen+"/"+ UUID.randomUUID()+picFile.getOriginalFilename();

        try {
            ossClient.putObject(bucketName, fileName, picFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "http://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+fileName;

    }

}